//
//  NSData+Encryption.m
//
//
//  Created by 王晓萌 on 17/4/19.
//  Copyright © 2017年 Facebook. All rights reserved.
//

#import "NSData+Encryption.h"
#import <CommonCrypto/CommonCrypto.h>


#define IV @"24d77bb6b61c8fc1"
@implementation NSData (Encryption)
- (NSData *)AES128EncryptWithKey:(NSString *)key {//加密
  char keyPtr[kCCKeySizeAES128+1];
  bzero(keyPtr, sizeof(keyPtr));
  [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
  
  char ivPtr[kCCKeySizeAES128+1];
  memset(ivPtr, 0, sizeof(ivPtr));
  [IV getCString:ivPtr maxLength:sizeof(ivPtr) encoding:NSUTF8StringEncoding];
  
  NSUInteger dataLength = [self length];
  size_t bufferSize = dataLength + kCCBlockSizeAES128;
  void *buffer = malloc(bufferSize);
  size_t numBytesEncrypted = 0;
    
  CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt,
                                        kCCAlgorithmAES128,
                                        kCCOptionPKCS7Padding,
                                        keyPtr,
                                        kCCBlockSizeAES128,
                                        ivPtr,
                                        [self bytes],
                                        dataLength,
                                        buffer,
                                        bufferSize,
                                        &numBytesEncrypted);
  if (cryptStatus == kCCSuccess) {
    return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
  }
  free(buffer);
  return nil;
}

@end
